<?php

class multitender_model_users extends multitender_model {
    private $last_visit_db;
    private $user_db;

    function __construct() {
        parent::__construct();
        $this->id         = & $this->conf['user']['id'];
        $this->joomla_id  = & $this->conf['user']['joomla_id'];
        $this->name       = & $this->conf['user']['name'];
        $this->right      = & $this->conf['user']['right'];
        $this->last_visit = & $this->conf['user']['last_visit'];

        $this->db = & $this->conf['dbs']['person'];
        if ( ! $this->db ) {
            trigger_error('Where DB person?');
            exit;
        }
    }

    public function get_user_id() {
        // гость, пропускаем
        if ($this->id === 0) {
            return $this->id;
        }

        // пытаемся найти в нашей базе по joomla_id        
        if ( is_null($this->id) && $this->joomla_id ) {
            if ( ($users = $this->db->GetRow("SELECT * FROM users WHERE joomla_id=$this->joomla_id")) ) {
                $this->right = $users['rights'];
                $this->id    = $users['Id'];
                $this->name  = $users['name'];
                $this->last_visit  = strtotime($users['last_visit']) ?
                        date('Ymd', strtotime($users['last_visit'])) : date('Ymd');
                $this->last_visit_db = $users['last_visit'];
                $this->user_db = $users;

                return $this->id;
            } else {
                return $this->add_user();
            }
        }

        if (empty($this->id)){ return false; }

        // делаем проверку на наличие пользователя в базе
        if ( ($users = $this->db->GetRow("SELECT * FROM users WHERE Id=$this->id")) ) {
            $this->right       = $users['rights'];
            $this->name        = $users['name'];
            $this->last_visit  = strtotime($users['last_visit']) ?
                    date('Ymd', strtotime($users['last_visit'])) : date('Ymd');
            $this->last_visit_db = $users['last_visit'];
            $this->user_db     = $users;

            return $users['Id'];
        } else {
            // для ботов joomla_id может и не быть
            if ( $this->id < 30 ) {
                return $this->add_bot();
            } else {
                trigger_error('Unknown user id');
                exit;
            }
        }
    }
    
    private function add_bot() {
        // поправить структуру таблицы users. Добавить возможность NULL для поля joomla_id
        $sql = "INSERT INTO users(Id, joomla_id, name, rights) VALUES(?,NULL,?,0)";
        if ($this->db->Execute($sql, array($this->id, $this->name))) {
            $this->id = $this->db->Insert_ID();
            return $this->id;
        } else {
            return false;
        }
    }

    private function add_user() {
        if (!$this->joomla_id) {
            $this->joomla_id = 0;
        }
        $sql="INSERT INTO users(joomla_id,name,rights) VALUES(?,?,?)";
        if ($this->db->Execute($sql,array($this->joomla_id, $this->name, $this->right))) {
            $this->id = $this->db->Insert_ID();
            
            $sql = "INSERT INTO access(user_id, todate, tenders, count_puchased) VALUES(?, ?, ?, ?)";
            $this->db->Execute($sql, array($this->id, '20200101', 0, 0));
            
            return $this->id;
        } else {
            return false;
        }
    }

    function get_user_by_ids($ids) {
        if (!$ids) {
            return false;
        }

        $sql="SELECT * FROM users WHERE Id IN (".implode($ids, ",").")";
        if ($names=$this->db->GetAll($sql)) {
            return $names;
        } else {
            return false;
        }
    }

    function get_list_moder() {
        $sql="SELECT * FROM users WHERE rights > 50";
        if ($moders = $this->db->GetAll($sql)) {
            return $moders;
        } else {
            return false;
        }
    }

    function set_last_visit() {
        $date_now = date('Y-m-d');
        if ( $date_now == $this->last_visit_db ) {
            return false;
        }
        $sql="UPDATE users SET last_visit='$date_now' WHERE id=$this->id";
        $this->last_visit = date('Ymd');
        return $this->db->Execute($sql);
    }

    function set_user_agent() {
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }

        $agent_now = trim($_SERVER['HTTP_USER_AGENT']);
        if (empty($agent_now)) {
            return false;
        }
        $agents = explode("\n", $this->user_db['user_agent']);

        $return = array();
        
        foreach ($agents as $a) {
            $a = trim($a);
            if (empty($a)) {
                continue;
            }
            $return[crc32($a)] = $a; // убираем повторы
        }

        $return = array_values($return);

        if ( in_array($agent_now, $return) ) {
            return false;
        } else {
            array_unshift($return, $agent_now); // в обратном порядке, снизу вверх
        }

        $sql="UPDATE users SET user_agent=? WHERE id=$this->id";
        return $this->db->Execute($sql, array(implode("\n", $return)));
    }

    function set_user_ip() {
        $ip_now = trim($_SERVER['REMOTE_ADDR']);
        $ips = explode("\n", $this->user_db['ip']);
        $return = array();
        foreach ($ips as $ip) {
            $ip = trim($ip);
            if (empty($ip)) {
                continue;
            }
            $return[crc32($ip)] = $ip; // убираем повторы
        }
        $return = array_values($return);

        if (in_array($ip_now, $return)) {
            return false;
        } else {
            array_unshift($return, $ip_now); // в обратном порядке, снизу вверх
        }

        $sql="UPDATE users SET ip=? WHERE id=$this->id";
        return $this->db->Execute($sql, array(implode("\n", $return)));
    }
}

